<?php
class CartsController extends AppController {
	var $uses = array('Orders','Product','Stock');
	var $components = array('Session');
	public function beforeFilter() {
        parent::beforeFilter();
		$this->Auth->allow();
		if(!$this->Session->check('cart')) $this->Session->write('cart',array()); 
    }
    
	public function index() {
		$rs = $this->Session->read('cart');
		$this->set(compact('rs'));
    }
	
	public function update(){pr($this->data);
		if(!empty($this->data)){
			$rs = $this->Session->read('cart');
			$rs[$this->data['cart']['key']]['amount'] = $this->data['cart']['amount'];			
			$this->Session->write('cart',$rs);
		}
		$this->Session->setFlash('Số lượng đã được cập nhật');
		$this->redirect('/gio-hang');
	}
	
	public function delete($id = null){
		if($id != null){
			$rs = $this->Session->read('cart');
			unset($rs[$id]);
			$this->Session->write('cart',$rs);
		}
		$this->Session->setFlash('Sản phẩm đã được xóa khỏi giỏ hàng');
		$this->redirect('/gio-hang');
	}
	
	public function deleteall(){
		$this->Session->delete('cart');
		$this->Session->setFlash('Giỏ hàng đã được xóa');
		$this->redirect('/gio-hang');
	}
	
	public function add(){		
		if(!empty($this->data)){
			$tmp = $this->Product->findById($this->data['Product']['id']);
			if($tmp){
				$cart = $this->Session->read('cart');
				$exists = false;
				foreach($cart as $key=>$item){
					if($item['id'] == $this->data['Product']['id'] && $item['size_name'] == $this->data['sizeval']){
						$cart[$key]['amount'] += $this->data['quantityval'];
						$exists = true;
						break;
					}
				}
				if($exists == false){
					//se check stock < so luong mua sau
					//$stock = $this->Stock->findByProductId($tmp['Product']['id']);
					$data = array(
						'id' => $this->data['Product']['id'],
						'product_code' => $tmp['Product']['product_code'],
						'name' => $this->data['Product']['name'],					
						'photo' => $tmp['Product']['photo'],
						'photo_dir' => $tmp['Product']['photo_dir'],
						'slug' => $tmp['Product']['slug'],
						'size_name' => $this->data['sizeval'],
						'amount' => $this->data['quantityval'],
						'price' => $tmp['Product']['price'],
					);
					array_push($cart,$data);
				}				
				$this->Session->write('cart',$cart);
				$this->Session->setFlash('Sản phẩm đã được thêm vào giỏ hàng');
			}			
		}
		$this->redirect('/gio-hang');
	}
}
